package com.alex.orderservice.service;

import com.alex.common.constants.CuileiQueueConstants;
import com.alex.common.message.CuileiOrderMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.UUID;

@Service
public class CuileiOrderService {

    private static final Logger logger = LoggerFactory.getLogger(CuileiOrderService.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 创建订单并发送消息
     * 这里模拟真实的订单创建流程
     *
     * @param userId 用户ID
     * @param productName 商品名称
     * @param amount 订单金额
     * @return 订单ID
     */
    public String createCuileiOrder(String userId, String productName, BigDecimal amount) {
        // 1. 生成订单ID（实际项目中可能从数据库获取）
        String orderId = "CUILEI_ORDER_" + UUID.randomUUID().toString().substring(0, 8);

        // 2. 创建订单消息对象
        CuileiOrderMessage orderMessage = new CuileiOrderMessage(
                orderId, userId, productName, amount, "CREATED"
        );

        logger.info("崔磊订单服务：开始处理订单 {}", orderMessage);

        // 3. 发送消息到支付队列
        // 就像把订单信息投递到支付部门的邮箱
        rabbitTemplate.convertAndSend(
                CuileiQueueConstants.CUILEI_ORDER_EXCHANGE,     // 交换机
                CuileiQueueConstants.CUILEI_PAYMENT_ROUTING_KEY, // 路由键
                orderMessage                                     // 消息内容
        );
        logger.info("崔磊订单服务：支付消息发送成功，路由键：{}",
                CuileiQueueConstants.CUILEI_PAYMENT_ROUTING_KEY);

        // 4. 发送消息到通知队列
        // 就像把订单信息投递到通知部门的邮箱
        rabbitTemplate.convertAndSend(
                CuileiQueueConstants.CUILEI_ORDER_EXCHANGE,
                CuileiQueueConstants.CUILEI_NOTIFICATION_ROUTING_KEY,
                orderMessage
        );
        logger.info("崔磊订单服务：通知消息发送成功，路由键：{}",
                CuileiQueueConstants.CUILEI_NOTIFICATION_ROUTING_KEY);

        return orderId;
    }


}
